<template>
	<view class="chatContainer">
		<view class="header">
			<view class="statusBar" :style="{width: screenWidth+'px'}"></view>
			<view class="headLeader" :style="{width: screenWidth+'px', height: headerHeight*1.3+'px'}">
				<view class="back" @click="back">
					<u-icon name="arrow-left" :size="50"></u-icon>
				</view>
				<view class="chatWith">
					{{info.nickname}}
				</view>
				<view class="otherOptions" style="width: 60upx; height: 60%;">
					
				</view>
			</view>
		</view>
		
		<view class="chatMainBox" :style="{height: screenHeight-headerHeight*4.3+'px', width: screenWidth+'px'}">
			<view class="history" :style="{width: screenWidth*0.96+'px'}">
				<view class="everMsg" v-for="(item, index) in historyList" :key="index" :style="{flexDirection: item.isMe?'row-reverse':'row'}">
						<u-avatar :src="item.avatar" :size="70" style="border: 2upx solid white;" :class="[item.isMe?'myAvatar':'othersAvatar']" @click="seeHome(item.userId)"></u-avatar>
						<view class="baseMsg" :class="[item.isMe?'myMsg':'othersMsg']">
							{{item.msg}}
						</view>
				</view>
			</view>
		</view>
			
		<view class="inputbar" :style="{height: headerHeight*2+'px', width: screenWidth+'px'}">
				<input :adjust-position="true" type="text" v-model="myText" :style="{width: screenWidth*0.7+'px', height: headerHeight*1.4+'px'}"></input>
				<view @click="send" class="send" :style="{width: screenWidth*0.15+'px', height: headerHeight*1.4+'px'}">发送</view>
		</view>
	</view>
</template>

<script>
	import {mapState} from 'vuex'
	export default{
		data(){
			return{
				info: {},
				heart:null,
				pollingTimer: null,
				screenHeight: 0,
				screenWidth: 0,
				headerHeight: 0,
				timeUtil:new Date(),
				myText: '',
				webSocketTask: null,
				webSocketFlag: false,
				listFlag: 0,
				sendObj:{
					//success: true,
					time: '',
					fromUser: '',
					toUser: '',
					message:''
				},
			}
		},
		methods:{
			back(){
				uni.setStorage({
					key:`${this.myId}_chat_with_'${this.info.id}`,
					data: this.historyList,
					success: (res) => {
						console.log('聊天记录保存成功, 缓存中的聊天记录为： ')
						let s = uni.getStorageSync(`${this.myId}_chat_with_'${this.info.id}`)
						console.log(s)
					}
				})
				
				uni.navigateBack({
					delta:1,
					success: () => {
						clearInterval(this.pollingTimer)
						this.pollingTimer = null
					}
				})
			},
			getTimeNow(){
				let t = new Date(this.timeUtil.getTime())
				return  t.getFullYear()+'-'+(t.getMonth()+1 < 10 ? '0'+(t.getMonth()+1) : t.getMonth()+1) + '-' +t.getDate() + ' '+t.getHours()+':'+t.getMinutes()+':'+t.getSeconds()
			},
			seeHome(id){
				if(id == this.myId){return;}
				uni.request({
					method:'GET',
					url:`http://162.14.102.246:8090/user/front/homePage/${id}`,
					header:{
						xdzn_token: this.$store.state.loginUser.token
					}
				}).then(res => {
					//console.log('获取数据',res.data.data.home)
					uni.navigateTo({
						url:"/pages/components/userHomeFrames/otherUserHome?info="+encodeURIComponent(JSON.stringify(res.data.data.home))
					})
				})
			},
			openPolling(){ //开启轮询获取消息列表
				this.pollingTimer = setInterval(() => {
					//console.log('轮询开启')
					//console.log(this.fromUser,this.toUser )
					setTimeout(() => {
						uni.request({
							url:`http://162.14.102.246:8090/user/chat/log/${this.fromUser}/${this.toUser}`,
							method:'POST',
							data:{
								xdzn_token: this.token,
								'Content-Type': 'application/x-www-form-urlencoded'
							}
						}).then(res => {
							if(res.data.code == 200){
								let from = res.data.data.fromList
								let to = res.data.data.toList
								
								let t1 = to[to.length-1].time
								let flag = this.historyList[this.historyList.length-1].time
								if(t1 <= flag){
									return;
								}else{
									to.forEach(item => {
										from.push(item)
									})
									
									from.sort((o1, o2) => {
										return o1.time - o2.time
									})
									
									to.forEach(item => {
										this.$store.state.loginUser.historyList.push({
											avatar: this.info.avatar,
											userId: this.info.id,
											msg: item.message,
											isMe: false,
											time: item.time
										})
									})
								}
								
								// let flag = from[from.length-1].time == this.historyList[this.historyList.length-1].time
								// if(flag){
								// 	return;
								// }else{
									
								// 	let o = from.find(obj => obj.item == this.historyList[this.historyList.length-1].time)
								// 	let p = from.indexOf(o)
									
								// 	for(let i = p; i < from.length; i++){
								// 		this.historyList.push({
								// 			avatar: from[i].fromUser == this.sendObj.fromUser ? this.sendObj.fromUser : this.sendObj.toUser,
								// 			userId: from[i].fromUser == this.sendObj.fromUser ? this.myId : this.info.id,
								// 			msg: from[i].message,
								// 			isMe: from[i].fromUser == this.sendObj.fromUser ? true : false,
								// 			time: from[i].time
								// 		})
								// 	}
								// }
								//console.log(data)
							}
						})
					}, 0)
				}, 3000)
			},
			// init(){
			// 	//uni.closeSocket()
			// 	this.webSocketTask = uni.connectSocket({
			// 		url: 'ws://192.168.31.146:8095/chat/private/chat',
			// 		header:{
			// 			xdzn_token: this.token
			// 		},
			// 		success: (res) => {
			// 			console.log('ws连接成功')
			// 			this.webSocketFlag = true
			// 		},
			// 		fail: (res) => {
			// 			console.log('ws链接失败', res)
			// 		}
			// 	})
				
			// 	if(this.webSocketFlag){
			// 		this.listenMessage()
			// 		this.webSocketTask.onOpen((res) => {
			// 			console.log('ws链接已经成功打开', res)
			// 			this.resetHeart()
			// 		})
			// 		this.webSocketTask.onError((res) => {
			// 			console.log('ws链接出现错误', res)
			// 		})
			// 	}
			// },
			// listenMessage(){ //监听服务器返回的消息
			// 	if(this.webSocketFlag){
			// 		this.webSocketTask.onMessage(res => {
			// 			console.log(res)
			// 			console.log('监听中---------------------')
			// 			//console.log(this.sendObj)
			// 			let msg = JSON.parse(res.data)
			// 			console.log(msg)
			// 			this.sendObj.fromUser = msg.fromUser
			// 		})
			// 	}
			// },
			getMessage(msg){
				let obj = {
					avatar: this.info.avatar,
					userId: this.info.id,
					msg:msg,
					isMe: false
				}
				
				this.historyList.push(obj)
			},
			// startHeart(){
			// 	let that = this
			// 	if(this.socketFlag){
			// 		this.heart = setInterval(() => {
			// 			this.socketTask.onMessage({
			// 				data:'ping',
			// 				success: () => {
			// 					return;
			// 				},
			// 				fail: (err) => {
			// 					console.log('连接断开，正在重新连接')
			// 					//that.init()
			// 				}
			// 			})
			// 		}, 15000)
			// 	}
			// },
			
			//心跳机制
			// resetHeart(){
			// 	clearInterval(this.heart)
			// 	this.startHeart()
			// },
			checkLink(){
				let that = this
				uni.sendSocketMessage({
					data: 'ping',
					success: () => {
						return;
					},
					fail: () => {
						that.init()
					}
				})
			},
			initHistory(){ //开启轮询获取消息列表
				uni.request({
					url:`http://162.14.102.246:8090/user/chat/log/${this.fromUser}/${this.toUser}`,
					method:'POST',
					data:{
						xdzn_token: this.token,
						'Content-Type': 'application/x-www-form-urlencoded'
					}
				}).then(res => {
					console.log(res)
					if(res.data.code == 200){
						let from = res.data.data.fromList
						let to = res.data.data.toList
						to.forEach(item => {
							from.push(item)
						})
						
						from.sort((o1, o2) => {
							return o1.time - o2.time
						})
						//console.log(from)
						from.forEach(item => {
							this.$store.state.loginUser.historyList.push({
								avatar: item.fromUser == this.sendObj.fromUser ? this.myAvatar : this.info.avatar,
								userId: item.fromUser == this.sendObj.fromUser ? this.myId : this.info.id,
								msg: item.message,
								isMe: item.fromUser == this.sendObj.fromUser ? true : false,
								time: item.time
							})
						})
						
						// let flag = from[from.length-1].time == this.historyList[this.historyList.length-1].time
						// if(flag){
						// 	return;
						// }else{
							
						// 	let o = from.find(obj => obj.item == this.historyList[this.historyList.length-1].time)
						// 	let p = from.indexOf(o)
							
						// 	for(let i = p; i < from.length; i++){
						// 		this.historyList.push({
						// 			avatar: from[i].fromUser == this.sendObj.fromUser ? this.sendObj.fromUser : this.sendObj.toUser,
						// 			userId: from[i].fromUser == this.sendObj.fromUser ? this.myId : this.info.id,
						// 			msg: from[i].message,
						// 			isMe: from[i].fromUser == this.sendObj.fromUser ? true : false,
						// 			time: from[i].time
						// 		})
						// 	}
						// }
						//console.log(data)
					}
				})
			},
			send(){
				if(!this.myText){return;}
				
				this.sendObj.message = this.myText
				console.log(this.sendObj)
				this.sendObj.time = this.timeUtil.getTime()
				//let send = JSON.stringify(this.sendObj)
				uni.request({
					url:'http://162.14.102.246:8090/user/chat/send',
					method:'POST',
					header:{
						xdzn_token: this.token,
						'Content-Type':'application/json'
					},
					data:this.sendObj
				}).then(res => {
					console.log(res)
					if(res.data.code == 200){
						let data = res.data.data
						console.log(data)
						this.historyList.push({
							avatar: this.myAvatar,
							userId: this.myId,
							msg: this.myText,
							isMe: true,
							time: this.timeUtil.getTime()
						})
						this.myText = ''
						//console.log('成功发送后的回调',data)
					}
				})
				//webSocket 消息发送方法
				// this.$ws.socketTask.send({
				// 	data:send, 
				// 	success: (res) => {
				// 		//console.log(res)
				// 		let newObj = {
				// 			avatar: this.myAvatar,
				// 			userId: this.myId,
				// 			msg: this.myText,
				// 			isMe: true
				// 		}
				// 		this.historyList.push(newObj)
				// 		this.myText = ''
						
				// 	},
				// 	fail:(res) => {
				// 		console.log(res)
				// 		uni.showToast({
				// 			icon:'error',
				// 			title:'发送失败，请稍后重试',
				// 			duration:1200
				// 		})
				// 	}	         
				// })
				
				
			},
			updateMsgList(userId){
				let flag = this.list.find(obj => obj.userId == userId)
				//console.log(flag)
				if(flag === undefined){return;}
				
				//若聊天记录没有初始化，则先读取缓存
				if(!this.historyList){
					let res = uni.getStorageSync(`${this.myId}_chat_with_'${userId}`)
					
					if(!res){
						uni.setStorage({
							key:`${this.myId}_chat_with_'${userId}`,
							data: [],
							success: (res) => {
								console.log('聊天缓存设置成功：', res)
							}
						})
					}else{
						this.historyList = res
					}
				}
				 
				flag.msgList.forEach((item) => {
					if(!item.isRead){
						item.userId = item.isMe ? this.myId : this.info.id
						item['avatar'] = item.isMe ? this.myAvatar : this.info.avatar
						this.historyList.push(item)
						item.isRead = true
					}
				})
			},
			// closeWebSocket(){
			// 	uni.onSocketOpen(() => {
			// 		uni.closeSocket({
			// 			success: () => {
			// 				console.log('ws链接已成功关闭')
			// 				this.webSocketFlag = false
			// 			}
			// 		})				 
			// 	})
			// },
			
		},
		mounted(){
			uni.getSystemInfo({
				success: (res) => {
					this.screenHeight = res.screenHeight
					this.screenWidth = res.screenWidth
					this.headerHeight = res.statusBarHeight
				}
			})
			//this.init()
			this.updateMsgList(this.info.id)
			// this.$ws.socketTask.onMessage(res => {
			// 	console.log(res)
			// })
			this.initHistory()
			//this.openPolling()
			this.sendObj.fromUser = this.fromUser
			this.sendObj.toUser = this.info.id
		},
		computed:{
			...mapState({
				myAvatar: state => state.loginUser.userBaseInfo.avatar,
				token: state => state.loginUser.token,
				myId: state => state.loginUser.userBaseInfo.id,
				// socketTask: state => state.webSocketUtil.socketTask,
				// socketFlag: state => state.webSocketUtil.flag
				list: state => state.loginUser.msgList,
				fromUser: state => state.webSocketUtil.fromUser,
				toUser: state => state.webSocketUtil.toUser,
				historyList: state => state.loginUser.historyList
			})
		},
		watch:{
			list:{
				handler(newList, oldList){
					this.updateMsgList(this.info.id)
				}  
			}
		},
		onLoad(options) {
			this.info = JSON.parse(decodeURIComponent(options.info))
			//this.sendObj.toUser = this.info.id
			// console.log(this.info)
			// console.log(this.info.id)
		},
		onUnload() {
			//this.closeWebSocket()
		}
	}
	
</script>

<style scoped>
	.chatContainer{
		display: flex;
		align-items: center;
		flex-direction: column;
	}
	.statusBar{
		height: var(--status-bar-height);
	}
	.header{
		display: flex;
		align-items: center;
		flex-direction: column;
		background-color: white;
	}
	.back{
		margin-left: 30upx;
	}
	.chatWith{
		color: dodgerblue;
	}
	.headLeader{
		width: 100%;
		font-size: 1rem;
		font-weight: 500;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.chatMainBox{
		background-color:rgba(245, 245, 245, 1.0);
		overflow-y: auto;
		overflow-x: hidden;
	}
	.history{
		margin: 0 auto;
	}
	.inputbar{
		background-color: #ffffff;
		position: fixed;
		z-index: 999;
		bottom: 0;
		display: flex;
		align-items: center;
		flex-direction: row;
		justify-content: space-around;
	}
	input{
		background-color: rgba(240, 240, 240, 1.0);
		border-radius: 50upx;
		padding-left: 20upx;
		padding-right: 20upx;
		margin-left: 10upx;
	}
	.send{
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 1rem;
		letter-spacing: 5upx;
		border-radius: 15upx;
		color: white;
		background-color: dodgerblue;
		border-radius: 50upx;
		margin-right: 10upx;
	}
	.everMsg{
		padding: 20upx 18upx 20upx 0upx;
		display: flex;
		width: 100%;
	}
	.baseAvatar{
		
	}
	.baseMsg{
		padding: 15upx 20upx 15upx 20upx;
		color: black;
		background-color: white;
		display: flex;
		flex-wrap: wrap;
		word-break: normal;
		border-radius: 18upx;
		max-width: 68%;
	}
	.myAvatar{
	}
	.myMsg{
		margin-right: 10upx;
	}
	.othersAvatar{
	}
	.othersMsg{
		margin-left: 10upx;
	}
</style>